package meijuli.com.join51.business.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.bumptech.glide.Glide;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultSubscriber;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import cn.finalteam.rxgalleryfinal.ui.RxGalleryListener;
import cn.finalteam.rxgalleryfinal.ui.base.IMultiImageCheckedListener;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.adapter.CustomAdapter;
import meijuli.com.join51.business.adapter.CustomHolder;
import meijuli.com.join51.business.aliyun.AliyunOSS;
import meijuli.com.join51.business.aliyun.UploadListener;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import meijuli.com.join51.business.model.Photos;
import com.jhx.common.widget.CommonDialog;
import com.jhx.common.widget.LoadingDialog;

import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.PermissionUtils;
import meijuli.com.join51.business.utils.SoftInputUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 相册管理
 *
 * @author Wizong 2017-05-19 13:09
 */
public class PhotosManagerActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    public static final String nowPage = "1";
    public static final String pageSize = "10";
    public static final int RESPONSE_SUCCESS = 0;
    public static final int REQUEST_CODE = 0x001001;
    private boolean setPermissions = false;
    private Call<HttpResponse<String>> mCall;
    private Call<HttpResponse<Photos>> call;
    TextView mTitleText;
    TextView mMenuText;
    Toolbar mToolbar;
    RecyclerView recyclerAddPhoto;
    Button mBtnSure;

    /**
     * 商品图片最多可选数量
     */
    private static final int MAX_SIZE = 9;

    private List<String> mUrlList = new ArrayList<>();
    private ArrayList<MediaBean> mImageList = new ArrayList<>();
    private ArrayList<MediaBean> mImgList = new ArrayList<>();
    private ArrayList<String> mCompressList = new ArrayList<>();
    private CustomAdapter<MediaBean> mAdapter;
    private int mCount = MAX_SIZE;
    private boolean isEdit = false;
    private String dmId = "";
    private ArrayList<MediaBean> mOldImageList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photos_manager);
        mTitleText = findViewById(R.id.toolbar_title);
        mMenuText = findViewById(R.id.text_menu);
        mToolbar = findViewById(R.id.toolbar);
        recyclerAddPhoto = findViewById(R.id.recycler_add_photo);
        mBtnSure = findViewById(R.id.btn_photo_manager);
        mBtnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onViewClicked();
            }
        });
        AliyunOSS.get().init();
        initToolbar();
        initData();
    }

    private void initToolbar() {
        mTitleText.setText("相册管理");
        mMenuText.setText("编辑");
        mMenuText.setVisibility(View.VISIBLE);
        checkEditStatus();
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mMenuText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isEdit = !isEdit;
                checkEditStatus();
            }
        });
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    private void checkEditStatus() {
        mBtnSure.setVisibility(isEdit ? View.VISIBLE : View.GONE);
        if (isEdit) {
            mMenuText.setText("取消");
            if(mImageList != null && mImageList.size() < MAX_SIZE) {
                mImageList.add(new MediaBean());
            }
        } else {
            mMenuText.setText("编辑");
            if (mOldImageList != null && mOldImageList.size() > 0) {
                mImageList.clear();
                mImageList.addAll(mOldImageList);
            }
        }
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void initData() {
        if (UserManager.get().checkUserNull(this)) {
            return;
        }

        mAdapter = new CustomAdapter<MediaBean>(mImageList, this, R.layout.item_add_pic, null) {
            @Override
            public void onBindData(CustomHolder holder, final int position, final MediaBean mediaBean) {
                final ImageView addImage = holder.findView(R.id.img_add);
                ImageView delImage = holder.findView(R.id.img_delete);
                if (TextUtils.isEmpty(mediaBean.getOriginalPath())) {
                    if (isEdit) {
                        addImage.setImageResource(R.mipmap.add_pic);
                        addImage.setVisibility(View.VISIBLE);
                    } else {
                        addImage.setVisibility(View.GONE);
                    }
                    delImage.setVisibility(View.GONE);
                } else {
                    String path = mediaBean.getOriginalPath();
                    if (path.toUpperCase(Locale.US).startsWith("HTTP://")) {
                        Glide.with(PhotosManagerActivity.this)
                                .load(mediaBean.getOriginalPath())
                                .error(R.mipmap.img_default)
                                .centerCrop()
                                .into(addImage);
                    } else {
                        Glide.with(PhotosManagerActivity.this)
                                .load(new File(mediaBean.getOriginalPath()))
                                .error(R.mipmap.img_default)
                                .centerCrop()
                                .into(addImage);
                    }
                    if (isEdit) {
                        delImage.setVisibility(View.VISIBLE);
                        addImage.setClickable(true);
                    } else {
                        delImage.setVisibility(View.GONE);
                        addImage.setClickable(false);

                    }
                }

                addImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (TextUtils.isEmpty(mediaBean.getOriginalPath())) {
                            mCount = MAX_SIZE - (mImageList.size() - 1);
                            takePictures(mCount);
                        } else {
                            Intent intent = new Intent(PhotosManagerActivity.this, PicturePreviewActivity.class);
                            intent.putParcelableArrayListExtra(PicturePreviewActivity.KEY_LIST, mImageList);
                            intent.putExtra(PicturePreviewActivity.KEY_INDEX, position);
                            startActivity(intent);
                        }
                    }
                });
                delImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MediaBean bean = mImageList.get(mImageList.size() - 1);
                        if (!TextUtils.isEmpty(bean.getOriginalPath())) {
                            mImageList.add(new MediaBean());
                        }
                        mImageList.remove(position);
                        mAdapter.updateView(mImageList);
                    }
                });
            }
        };
        recyclerAddPhoto.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerAddPhoto.setEnabled(false);
        recyclerAddPhoto.setAdapter(mAdapter);
        queryPhotos();
    }

    private void queryPhotos() {
        call = ApiManager.get().getApiService(ApiService.class).getBusinessAlbumList(nowPage, pageSize);
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<Photos>() {

            @Override
            public void onSuccess(String url, Photos data) {
                if (data != null && !TextUtils.isEmpty(data.getImgUrl())) {
                    dmId = data.getDmId();
                    String[] photosList = data.getImgUrl().split(",");
                    for (String photoUrl : photosList) {
                        MediaBean mediaBean = new MediaBean();
                        mediaBean.setOriginalPath(photoUrl);
                        mImageList.add(mediaBean);
                    }
                }
                mOldImageList.addAll(mImageList);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private void uploadPhotos(StringBuilder buffer) {
        mCall = ApiManager.get().getApiService(ApiService.class).uploadBusinessPhoto(buffer.toString());
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<String>() {
            @Override
            public void onSuccess(String url, String data) {
                Toast.makeText(PhotosManagerActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                finish();
            }
        });
    }

    private void deletePhotos() {
        if (TextUtils.isEmpty(dmId)) {
            mCall = ApiManager.get().getApiService(ApiService.class).deleteBusinessAlbumById(dmId);
            HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<String>() {

                @Override
                public void onSuccess(String url, String data) {
                    Toast.makeText(PhotosManagerActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    finish();
                }

                @Override
                public void onError(String url, int errorCode, String errorMsg) {
                    super.onError(url, errorCode, errorMsg);
                    finish();
                }
            });
        }
    }

    /**
     * 调用图片选择器
     */
    public void takePictures(final int maxSize) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            showPictureSelector(maxSize);
            return;
        }
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            showPictureSelector(maxSize);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CommonDialog dialog = new CommonDialog(this);
                dialog.setMessage("为了保证聚惠侠商家版可以正常使用,请在设置-应用-聚惠侠商家版-权限，开启拍照权限");
                dialog.setConfirmBtn("设置");
                dialog.show();
                dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                    @Override
                    public void onConfirmClick(View view) {
                        setPermissions = true;
                        PermissionUtils.getInstance().toSetting(PhotosManagerActivity.this);
                    }

                    @Override
                    public void onCancelClick(View view) {
                        ToastUtil.getInstance().showToast("拍照权限被拒绝");
                    }
                });
            }else {
                EasyPermissions.requestPermissions(this, "应用需要拍照权限，请授权",
                        100,
                        Manifest.permission.CAMERA);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(setPermissions) {
            checkPermissions();
        }
    }

    private void checkPermissions() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            setPermissions = false;
            showPictureSelector(MAX_SIZE);
        }  else {
            ToastUtil.getInstance().showToast("拍照权限已拒绝");
        }
    }


    /**
     * 显示图片选择器
     *
     * @param maxSize
     */
    public void showPictureSelector(int maxSize) {
        SoftInputUtil.get().hideSoftKeyboard(PhotosManagerActivity.this);
        //多选图片
        RxGalleryFinal.
                with(PhotosManagerActivity.this).
                image().
                multiple().
                maxSize(maxSize).
                imageLoader(ImageLoaderType.GLIDE).
                subscribe(new RxBusResultSubscriber<ImageMultipleResultEvent>() {
                    @Override
                    protected void onEvent(ImageMultipleResultEvent imageResult) throws Exception {
                        final List<MediaBean> imgList = imageResult.getResult();
                        if (mImageList.size() <= MAX_SIZE) {
                            mImageList.remove(mImageList.size() - 1);
                            for (int i = 0; i < imgList.size(); i++) {
                                final MediaBean bean = imgList.get(i);
                                if (!TextUtils.isEmpty(bean.getOriginalPath())) {
                                    mImageList.add(bean);
                                }
                            }
                            if (mImageList.size() < MAX_SIZE) {
                                mImageList.add(new MediaBean());
                            }
                        }
                        mAdapter.updateView(mImageList);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        CrashReport.postCatchedException(e);
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                }).openGallery();
        multiListener();
    }

    /**
     * 多选事件都会在这里执行
     */
    public void multiListener() {
        //得到多选的事件
        RxGalleryListener.getInstance().setMultiImageCheckedListener(new IMultiImageCheckedListener() {
            @Override
            public void selectedImg(Object t, boolean isChecked) {
                //这个主要点击或者按到就会触发，所以不建议在这里进行Toast
            }

            @Override
            public void selectedImgMax(Object t, boolean isChecked, int maxSize) {
                Toast.makeText(getBaseContext(), "你最多只能选择" + maxSize + "张图片", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 启动压缩
     *
     * @param path
     */
    public void startCompression(String path) {
        try {
            File imgFile = new File(path);
            if (!imgFile.exists() || imgFile.length() == 0) {
                CrashReport.postCatchedException(new RuntimeException("所选文件为空"));
                ToastUtil.getInstance().showToast(this, "获取图片失败, 请重试!");
                return;
            }
            Luban.with(this)
                    .load(imgFile)
                    .setCompressListener(new OnCompressListener() {

                        @Override
                        public void onStart() {
                            //  压缩开始前调用，可以在方法内启动 loading UI
                            if(mLoadingDialog == null) {
                                mLoadingDialog = new LoadingDialog(PhotosManagerActivity.this);
                                mLoadingDialog.setTitle("正在上传图片...");
                            }
                            if(!mLoadingDialog.isShowing()) {
                                mLoadingDialog.show();
                            }
                        }

                        @Override
                        public void onSuccess(File file) {
                            mCompressList.add(file.getAbsolutePath());
                            if(mCompressList.size() < mImgList.size()) {
                                startCompression(mImgList.get(mCompressList.size()).getOriginalPath());
                            } else {
                                //  压缩成功后，上传到阿里云
                                uploadHeadImage(mCompressList.get(0));
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            //  当压缩过去出现问题时调用
                            mLoadingDialog.dismiss();
                            ToastUtil.getInstance().showToast("图片压缩失败，请重试");
                            CrashReport.postCatchedException(e);
                        }
                    }).launch();    //启动压缩
        } catch (Exception e) {
            ToastUtil.getInstance().showToast("图片压缩失败，请重试");
            CrashReport.postCatchedException(e);
            CrashReport.postCatchedException(e);
        }
    }

    /**
     * 上传图片
     *
     * @param picPath
     */
    private void uploadHeadImage(String picPath) {
        try {
            AliyunOSS.get().upload(picPath, new UploadListener() {
                @Override
                public void onSuccess(String cloudKey, String sourceFilePath) {
                    mUrlList.add(cloudKey);
                    if(mUrlList.size() < mCompressList.size()) {
                        uploadHeadImage(mCompressList.get(mUrlList.size()));
                    } else {
                        mLoadingDialog.dismiss();
                        startRequest();
                    }
                }

                @Override
                public void onProgress(String cloudKey, long progress, long total) {

                }

                @Override
                public void onFailure(String cloudKey, ClientException exception) {
                    ToastUtil.getInstance().showToast("上传失败，请重试~");
                    CrashReport.postCatchedException(exception);
                }
            });
        } catch (FileNotFoundException e) {
            mLoadingDialog.dismiss();
            CrashReport.postCatchedException(e);
            ToastUtil.getInstance().showToast("上传失败，请重试~");
        }
    }

    /**
     * 向服务器发起请求
     */
    public void startRequest() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < mUrlList.size(); i++) {
            buffer.append(mUrlList.get(i));
            if (i < mUrlList.size() - 1) {
                buffer.append(",");
            }
        }
        uploadPhotos(buffer);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 以下方法将把权限结果执行给EasyPermission
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        showPictureSelector(mCount);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        List<String> permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.CAMERA);
        checkPermission(permissionList, "该功能需要使用您的相机，请前往设置-权限管理，开启拍照权限");
    }

    public void onViewClicked() {
        mCompressList.clear();
        mUrlList.clear();
        if (mImageList.size() <= 1) {
            ToastUtil.getInstance().showToast("请添加图片");
        } else {
            MediaBean media = mImageList.get(mImageList.size() - 1);
            if (TextUtils.isEmpty(media.getOriginalPath())) {
                mImageList.remove(mImageList.size() - 1);
            }
            if (mImageList.size() <= 0) {
                deletePhotos();
            } else {

                for (int i = 0; i < mImageList.size(); i++) {
                    final String path = mImageList.get(i).getOriginalPath();
                    if (!TextUtils.isEmpty(path)) {
                        if (path.toUpperCase(Locale.US).startsWith("HTTP://")) {
                            mUrlList.add(path);
                        } else {
                            mImgList.add(mImageList.get(i));
                        }
                    }
                }

                if(mImgList.size() > 0) {
                    startCompression(mImgList.get(0).getOriginalPath());
                }

                //全部都是网络图片，直接请求
                if (mUrlList.size() == mImageList.size()) {
                    startRequest();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AliyunOSS.get().recycler();
    }
}
